package com.artisan.si.controller;

import com.artisan.si.model.Order;
import com.artisan.si.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 订单控制器
 * 接收 HTTP 请求并将订单发送到 Spring Integration 流程中处理
 */
@RestController
@RequestMapping("/orders")
@CrossOrigin(origins = "*") // 允许跨域请求（开发环境）
public class OrderController {

    private static final Logger logger = LoggerFactory.getLogger(OrderController.class);
    
    private final MessageChannel inputChannel;
    private final OrderService orderService;

    /**
     * 构造函数注入消息通道和订单服务
     * @param inputChannel Spring Integration 的输入通道
     * @param orderService 订单服务
     */
    public OrderController(MessageChannel inputChannel, OrderService orderService) {
        this.inputChannel = inputChannel;
        this.orderService = orderService;
    }

    /**
     * 创建订单的 REST 端点
     * @param order 订单信息（从请求体中获取）
     * @return 响应信息
     */
    @PostMapping
    public Map<String, Object> createOrder(@RequestBody Order order) {
        logger.info("接收到订单创建请求: {}", order);
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            // 简单验证
            if (order.getQuantity() <= 0) {
                response.put("success", false);
                response.put("message", "订单数量必须大于0");
                logger.warn("订单数量无效: {}", order);
                return response;
            }
            
            // 将订单封装为消息并发送到集成流程
            boolean sent = inputChannel.send(new GenericMessage<>(order));
            
            if (sent) {
                response.put("success", true);
                response.put("message", "订单已成功提交处理: " + order.getProduct());
                response.put("order", order);
                logger.info("订单已发送到集成流程: {}", order.getProduct());
            } else {
                response.put("success", false);
                response.put("message", "订单提交失败，请稍后重试");
                logger.error("订单发送到集成流程失败: {}", order);
            }
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "处理订单时发生错误: " + e.getMessage());
            logger.error("处理订单请求时发生异常", e);
        }
        
        return response;
    }

    /**
     * 获取所有订单（测试用）
     * @return 简单的状态信息
     */
    @GetMapping("/status")
    public Map<String, Object> getStatus() {
        Map<String, Object> status = new HashMap<>();
        status.put("service", "Spring Integration Order Service");
        status.put("status", "运行中");
        status.put("integration_channel", "inputChannel");
        status.put("h2_console", "http://localhost:8080/h2-console");
        return status;
    }

    /**
     * 直接保存订单（绕过 Spring Integration，用于测试）
     * @param order 订单信息
     * @return 响应信息
     */
    @PostMapping("/direct")
    public Map<String, Object> createOrderDirect(@RequestBody Order order) {
        logger.info("直接保存订单请求: {}", order);
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            Order savedOrder = orderService.handleOrder(order);
            response.put("success", true);
            response.put("message", "订单直接保存成功");
            response.put("order", savedOrder);
            logger.info("订单直接保存成功: id={}", savedOrder.getId());
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "直接保存失败: " + e.getMessage());
            logger.error("直接保存订单失败", e);
        }
        
        return response;
    }

    /**
     * 健康检查端点
     * @return 健康状态
     */
    @GetMapping("/health")
    public Map<String, String> health() {
        Map<String, String> health = new HashMap<>();
        health.put("status", "UP");
        health.put("service", "OrderController");
        return health;
    }
}
